package mysql;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import java.sql.Connection;
import java.util.ArrayList;

public class DB {
	
	private Connection conn;
	private PreparedStatement neighborQuery;
	
	public DB(String url, String user, String password){
	
		try {
			// load mysql driver
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			
			// create connection
			// url "jdbc:mysql://localhost/mysql_db"
		    conn = DriverManager.getConnection(url, user, password);
		    neighborQuery = conn.prepareStatement("SELECT uid2 FROM facebook_edge WHERE uid1 = ?");
		    
		} catch (Exception e){
			e.printStackTrace();
		}
	}
	
	
	public ArrayList<Integer> getNeighbors(int nodeID) throws SQLException{
		ArrayList<Integer> neighbors = new ArrayList<Integer>();
		
		neighborQuery.setInt(1, nodeID);
		ResultSet rs = neighborQuery.executeQuery();
		while(rs.next()){
			neighbors.add(rs.getInt(1));
		}
		rs.close();
		
		return neighbors;

	}
	
	public int getNumAgeRange(int min, int max) throws SQLException{
		int size = 0;
		
		PreparedStatement query = conn.prepareStatement("SELECT count(*) FROM facebook_node Where facebook_node.age > ? and facebook_node.age < ?;");
		query.setInt(1, min);
		query.setInt(2, max);
		ResultSet rs = query.executeQuery();
		rs.next();
		size = rs.getInt(1);
		
		
		rs.close();
		
		return size;
	}
	
	public ArrayList<Integer> getRandIDs(int size) throws SQLException{
		ArrayList<Integer> list = new ArrayList<Integer>();
		
		PreparedStatement query = conn.prepareStatement("SELECT count(*) FROM facebook_node Where facebook ORDER by RAND() LIMIT ?");
		query.setInt(1, size);
		ResultSet rs = query.executeQuery();
		while(rs.next()){
			list.add(rs.getInt(1));
		}
		
		rs.close();
		
		return list;
	}
	
	public void close() throws SQLException{
		this.conn.close();
	}
	
	// testing
	public static void main(String[] args) throws SQLException {
		DB db = new DB("jdbc:mysql://localhost/mysql_db" , "root", "password");
		ArrayList<Integer> neighbors = db.getNeighbors(1);
		
		for(int neighbor : neighbors){
			System.out.println("Neighbor: " + neighbor);
		}
		
	}
	
	
}


